#include <kutils.h>
#include "syscall.h"
#include "memory.h"
#include "paging.h"
#include "display.h"

void mem_alloc_handler(syscall_regs_t *r);
void mem_free_handler(syscall_regs_t *r);
void mem_info_handler(syscall_regs_t *r);

extern address_space_t* active_space;
extern u32int free_mem_end;
extern u32int page_size;
s32int mem_frame_is_used(u32int addr);

void mem_alloc_handler(syscall_regs_t *r)
{
	write_string(" alloc ");
	write_hex(r->arg1); write_string("..");
	write_hex(r->arg2);
	r->success = (u32int)page_alloc(active_space, r->arg1, r->arg2);
}

void mem_free_handler(syscall_regs_t *r)
{
	//write_string(" free ");
	//TODO: implement
	r->success = 0;
}

void mem_info_handler(syscall_regs_t *r)
{
	u32int used_bytes = 0;
	u32int i = 0;
	for(i = 0; i < free_mem_end; i += page_size)
	{
		if(mem_frame_is_used(i))
		{
			used_bytes += page_size;
		}
	}

	r->res1 = free_mem_end;
	r->res2 = used_bytes;
	r->success = 1;
}

void init_mem_interface(void)
{
	install_syscall(SYS_PAGE_ALLOC, mem_alloc_handler);
	install_syscall(SYS_PAGE_FREE, mem_free_handler);
	install_syscall(SYS_MEM_INFO, mem_info_handler);
}
